package org.finesys.common.log.trace.interceptor.okhttp3;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.finesys.common.log.trace.interceptor.AbstractInterceptor;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.StringUtils;

import java.io.IOException;

import static org.finesys.common.log.constants.TraceConstants.*;

@Slf4j
public class TraceIdOkhttp3Interceptor extends AbstractInterceptor implements Interceptor {

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {

        Request request = chain.request();
        try {
            String traceId = getTraceId();
            String spanId = getSpanId();
            String parentId = getParentId();
            Request.Builder builder = request.newBuilder();
            if (StringUtils.hasText(traceId)) {
                builder.addHeader(TRACE_ID, traceId);
            }
            if (StringUtils.hasText(traceId)) {
                builder.addHeader(SPAN_ID, spanId);
            }
            if (StringUtils.hasText(traceId)) {
                builder.addHeader(PARENT_ID, parentId);
            }
            request = builder.build();
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(LogstashUtil.exceptionMarker(), "Okhttp3 http header set traceId exception!", e);
            }
        }
        super.executeBefore(OKHTTP_CLIENT_EXEC_BEFORE);
        Response response = chain.proceed(request);
        super.executeAfter(OKHTTP_CLIENT_EXEC_AFTER);
        return response;
    }
}
